##########################################################
#       Go  enrichment plot                              #
#       data Aug 13, 2019                                #
#       Shawn Wang                                       #
##########################################################
library(ggplot2)
library(dplyr)
library(magrittr)
library(stringr)
options(stringsAsFactors = F)
## introduce shell parameters to R
Args<-commandArgs(T)
## The 1st parameters is the file path
#fp = "~/14.Heterosis/06.WGCNA/01.leaf/01.GO.enrich/"
fp <- Args[1]
print(fp)
####===========step1 import file===================
setwd(fp)
path.raw <- fp
fileNames.raw <- dir(path.raw, pattern = ".xls") 
filePath.raw <- sapply(fileNames.raw, function(x){ 
  paste(path.raw,x,sep='/')})   
data.raw <- lapply(filePath.raw, function(x){
  read.table(x, sep = "\t",header = TRUE,quote = "",stringsAsFactors = FALSE)}) 
## The out put file name
name = sub(pattern = ".GO.Enrichment.final.xls",replacement = "",x = fileNames.raw)
####===========step1 data clearising===================
font.size = 12
data.clean <- list()
x <- list()
y <- list()
Gene_Number <- list()
Qvalue <- list()
for (i in c(1:length(name))) {
  ## 1.0 Pick out the columns 
  data.clean[[i]] = data.frame(id = factor(data.raw[[i]][,2], levels = data.raw[[i]][,2]),
                               ratio = data.raw[[i]][,7]/data.raw[[i]][,9],
                               Gene_Number = data.raw[[i]][,7],
                               Qvalue = data.raw[[i]][,12])
  data.clean[[i]] = data.clean[[i]][order(data.clean[[i]]$Qvalue),]
  
  ifelse(nrow(data.clean[[i]]) <= 30,
          data.clean[[i]] <- data.clean[[i]],
          data.clean[[i]] <- data.clean[[i]][1:30,])
  y <- as.character(data.clean[[i]][,1])
  for (j in 1:length(y)) {
    ifelse(nchar(y[j]) < 30,
           y[j] <- y[j],
           y[j] <- paste(str_sub(y[j],1,30),"...",sep = ""))
  }
  
  x <- data.clean[[i]][,2]
  Gene_Number <- data.clean[[i]][,3]
  Qvalue <- data.clean[[i]][,4]
  title <- paste(name[i],"Top 30 GO enrichment result"," ")
  p.base = ggplot(data.clean[[i]], aes(x=x, y=y))+
    geom_point(aes(color = Qvalue, size = Gene_Number))+
    scale_color_continuous(low="red", high="blue", guide=guide_colorbar(reverse=TRUE))+
    scale_size_continuous(range=c(0, 8))+
    labs(y=NULL) +
    ggtitle(title)+
    theme_bw() +
    theme(axis.text.x = element_text(colour = "black",
                                     size = font.size, vjust =1 ),
          axis.text.y = element_text(colour = "black",
                                     size = font.size, hjust =1 ),
          axis.title = element_text(margin=margin(10, 5, 0, 0),
                                    color = "black",size = font.size),
          axis.title.y = element_text(angle=90))+ 
    labs(x = "Gene_Ratio")
  
  ggsave(plot = p.base,
         filename = paste(name[i],".enrichment.bubbleplot.pdf",sep = ""), 
         width = 10, height = 10) 
  
}



